<?php
/**
 * Created by PhpStorm
 * User: lcz
 * Date: 2019/9/10
 * Time: 22:27
 * 购物车
 */

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\GoodsSpec;
use think\Db;

class Cart extends Api {
	/**
	 * 列表
	 */
	public function index(){
		$rows = Db::name('cart')->alias('c')
			->join('goods g', 'c.goods_id = g.id', 'left')
			->join('goodsSpec s', 'c.goods_spec_id = s.id', 'left')
			->where([
			'c.user_id' => $this->auth->id,
			'c.status' => \app\common\model\Cart::STATUS_NORMAL])
			->field('c.id, c.goods_id, c.goods_spec_id, c.number, g.name, g.image, g.status, g.price, g.market_price, g.number_store, s.name as spec_name, s.image as spec_image, s.price as spec_price, s.store_count as spec_store')
			->order(['c.update_time' => 'desc'])
			->select();
		
		$return = [
			'list' => [],
			'fail_list' => [],
		];
		if($rows) {
			foreach ($rows as $row) {
				if($row['status'] != \app\common\model\Goods::STATUS_SALE) {
					$return['fail_list'][] = $row;
				} else {
					$return['list'][] = $row;
				}
			}
		}
		
		$this->success('查询成功', $return);
	}
	
	
	/**
	 * 添加
	 */
	public function add(){
		$data = $this->request->post();
		$check = new \app\common\validate\Cart();
		if(!$check->check($data)) {
			$this->error($check->getError());
		}
		
		//查找商品是否有规格
		$spec = Db::name('goodsSpec')
			->where(['goods_id' => $data['goods_id'], 'status' => GoodsSpec::STATUS_Y])
			->column('name', 'id');
		if($spec && (!$data['goods_spec_id'] || !in_array($data['goods_spec_id'], array_keys($spec)))) {
			$this->error('请选择商品规格');
		}
		
		$userId = $this->auth->id;
		$data['user_id'] =  $userId;
		
		//查找是否已经加入过购物车且是正常状态
		$model = new \app\common\model\Cart();
		$row = $model->where([
			'user_id' => $userId,
			'goods_id' => $data['goods_id'],
			'goods_spec_id' => $data['goods_spec_id'],
			'status' => $model::STATUS_NORMAL])
			->find();
		
		if($row) {
			if(isset($data['id'])) {
				$res = $model->save(['number' => $data['number']], ['id' => $data['id']]);
			} else {
				$res = $model->where(['id' => $row['id']])->setInc('number', $data['number']);
			}
		} else {
			$res = $model->allowField(true)
				->isUpdate(false)->save($data);
		}
		
		if($res !== false) {
			$count = Db::name('cart')
				->where(['user_id' => $userId, 'status' => $model::STATUS_NORMAL])
				->sum('number');
			$this->success('操作成功', ['number' => $count]);
		} else {
			$this->error('操作出错');
		}
	}
	
	
	/**
	 * 删除
	 */
	public function del(){
		$ids = $this->request->post('ids');
		!$ids && $this->error('参数错误');
		
		$model = new \app\common\model\Cart();
		$res = $model
			->save(['status' => $model::STATUS_DELETE],
				['id' => ['in', $ids], 'user_id' => $this->auth->id]);
		
		if($res === false) {
			$this->error('删除出错');
		} else {
			$this->success('删除成功');
		}
	}
}
